package com.yiba.vpn.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.yiba.vpn.config.Config;
import com.yiba.vpn.config.ResultStatus;
import com.yiba.vpn.domain.User;
import com.yiba.vpn.dto.SuperPojo;
import com.yiba.vpn.model.ResultModel;
import com.yiba.vpn.repository.UserRepository;

/**
 * @author : tang
 * @createtime ：2018年1月29日 上午11:55:46
 * 
 */
@Service
public class InviteService {

	private Logger LOGGER = LoggerFactory.getLogger(InviteService.class);

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private Config config;

	public String doinvite(String sign) {
		try {
			User user = userRepository.findByVpnId(sign);
			if (user != null) {
				sign = user.getVpnId();
				// 是否对此次点击做记录
			} else {
				sign = null;
			}
		} catch (Exception e) {
			LOGGER.error("执行邀请跳转时查询用户信息异常" + e);
		}
		return sign;
	}

	public String createUrl(String account) {
		User user = null;
		try {
			user = userRepository.findByAccount(account);
		} catch (Exception e) {
			LOGGER.error("生成邀请连接时查询用户信息异常" + e);
		}

		if (user != null) {
			return createUrl(user);
		} else {
			return null;
		}
	}

	private ResponseEntity<ResultModel> createInviteUrl(User user) {
		SuperPojo superPojo = new SuperPojo();
		String url = createUrl(user);
		return new ResponseEntity<>(ResultModel.ok(superPojo.setProperty("url", url)), HttpStatus.OK);
	}

	private String createUrl(User user) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("yq_");
		buffer.append(user.getVpnId());
		return config.getHost().replace("www", buffer.toString());
	}
	

	public ResponseEntity<ResultModel> showInviteInfo(User user) {
		if (user == null) {
			return new ResponseEntity<>(ResultModel.error(ResultStatus.REQUEST_PARAMS_ERROR), HttpStatus.OK);
		}
		try {
			user = userRepository.findByAccount(user.getAccount());
		} catch (Exception e) {
			LOGGER.error("生成邀请连接时查询用户信息异常" + e);
		}
		if (user == null) {
			return new ResponseEntity<>(ResultModel.error(ResultStatus.REQUEST_PARAMS_ERROR), HttpStatus.OK);
		}
		return createInviteUrl(user);
	}

}
